<?php
/**
 * 定时器全量媒资补全
 * pan.liang
 */
header("Content-type: text/html; charset=utf-8");
ini_set('display_errors', 1);
set_time_limit(0);
include_once dirname(dirname(__FILE__)) . '/mgtv_v2/mgtv_init.php';
include_once dirname(dirname(__FILE__)) . '/api_v2/nn_const.php';
include_once dirname(dirname(__FILE__)) . '/api_v2/common.php';
include_once dirname(dirname(__FILE__)) . '/nn_logic/nl_common.func.php';

class timer_execute extends nn_timer
{
    public $str_date = null;
    public $str_date_time = null;
    public $arr_full_assets_site = array();
    
    /**
     * 定时器初始化
     * @see nn_timer::action()
     */
    public function action($params = null)
    {
        $this->msg('开始执行...');
        $this->init($params);
        $this->msg('执行结束...');
    }
    
    /**
     * 初始化
     */
    public function init($params=null)
    {
        include_once dirname(dirname(__FILE__)) . '/nn_logic/full_assets/full_assets.class.php';
        include_once dirname(dirname(__FILE__)) . '/nn_logic/full_assets/full_assets_site.class.php';
        include_once dirname(dirname(__FILE__)) . '/api_v2/control/standard/sync_source.php';
        $str_third_playbill_pool = $params["bk_queue_value"];
        if(strlen($str_third_playbill_pool) <1 || $str_third_playbill_pool !='thrid_full_assests')
        {
            $this->msg("[redis节目单池中返回数据为空]".$str_third_playbill_pool);
            return ;
        }
        $result_query = nl_full_assets::timer_query($this->obj_dc, $this->arr_params['bk_queue_config']['nns_ext_info']['data_num'], $this->arr_params['bk_queue_config']['nns_ext_info']['execute_num']);
        if($result_query['ret'] !=0)
        {
            $this->msg(var_export($result_query,true));
            return ;
        }
        if(!isset($result_query['data_info']) || !is_array($result_query['data_info']) || empty($result_query['data_info']))
        {
            $this->msg('sql查询到任何队列需要执行的数据：'.var_export($result_query,true));
            return ;
        }
        $result_assets_site = nl_full_assets_site::timer_query($this->obj_dc);
        if(!isset($result_assets_site['data_info']) || !is_array($result_assets_site['data_info']) || empty($result_assets_site['data_info']))
        {
            $this->msg('sql查询站点数据：'.var_export($result_assets_site,true));
            return ;
        }
        foreach ($result_assets_site['data_info'] as $site_val)
        {
            $this->arr_full_assets_site[]=$site_val['nns_siteid'];
        }
        $result_query = $result_query['data_info'];
        return $this->add_asset($result_query);
    }
    
    /**
     * 添加媒资
     * @param unknown $result_query
     */
    public function add_asset($result_query)
    {
        $temp_arr_data=array();
        foreach ($result_query as $query_val)
        {
            $result_edit = nl_full_assets::edit_sql($this->obj_dc, "update nns_full_assets set nns_execute_time=nns_execute_time+1,nns_modify_time='".date("Y-m-d H:i:s")."' where nns_id='{$query_val['nns_id']}'");
            if(isset($temp_arr_data[$query_val['nns_cp_id']]))
            {
                if(empty($temp_arr_data[$query_val['nns_cp_id']]) || !is_array($temp_arr_data[$query_val['nns_cp_id']]))
                {
                    continue;
                }
            }
            else
            {
                $result_cp = nl_cp::query_by_id($this->obj_dc, $query_val['nns_cp_id']);
                if($result_cp['ret'] !=0 || !isset($result_cp['data_info']) || !is_array($result_cp['data_info']) || empty($result_cp['data_info']))
                {
                    continue;
                }
                $temp_arr_data[$query_val['nns_cp_id']]['nns_name'] = $result_cp['data_info']['nns_name'];
                $temp_arr_data[$query_val['nns_cp_id']]['nns_config'] = (isset($result_cp['data_info']['nns_config']) && strlen($result_cp['data_info']['nns_config']) >0) ? json_decode($result_cp['data_info']['nns_config'],true) : null;
            }
            $result = $this->get_content_by_third(trim($query_val['nns_asset_import_id']),$this->handel_asset_name($query_val['nns_asset_name']));
            $result['reason'] = addslashes($result['reason']);
            if($result['ret'] == 0 && isset($result['data_info']) && !empty($result['data_info']) && is_array($result['data_info']))
            {
                $asset_data = $this->make_asset($result['data_info'],$query_val['nns_cp_id']);
                if(empty($asset_data))
                {
                    $edit_data = array(
                        'nns_state'=>3,
                        'nns_reason'=>"数据错误",
                    );
                    $this->msg('执行结果：数据错误');
                    $result_edit = nl_full_assets::edit($this->obj_dc, $edit_data, $query_val['nns_id']);
                    continue;
                }
                $flag = $asset_data['flag'];
                unset($asset_data['flag']);
                $result_indatabase = $this->in_database($asset_data,$query_val['nns_cp_id'],$temp_arr_data);
                if($result_indatabase['ret'] == 0)
                {
                    $edit_data = array(
                        'nns_state'=>$flag ? 2 : 1,
                    );
                    $result_edit = nl_full_assets::edit($this->obj_dc, $edit_data, $query_val['nns_id']);
                }
                else
                {
                    $edit_data = array(
                        'nns_state'=>3,
                        'nns_reason'=>addslashes($result_indatabase['reason']),
                    );
                    $result_edit = nl_full_assets::edit($this->obj_dc, $edit_data, $query_val['nns_id']);
                }
            }
            else
            {
                $this->msg('执行结果：'.var_export($result,true));
                $edit_data = array(
                    'nns_reason'=>$result['reason'],
                );
                if($result['ret'] == 0)
                {
                    $edit_data['nns_state'] = '3';
                }
                $result_edit = nl_full_assets::edit($this->obj_dc, $edit_data, $query_val['nns_id']);
            }
            if($result_edit['ret'] !=0)
            {
                $this->msg(var_export($result_edit,true));
            }
        }
        return;
    }
    
    /**
     * 数据入库
     * @param unknown $asset_data
     * @param unknown $cp_id
     * @param unknown $temp_arr_data
     */
    public function in_database($asset_data,$cp_id,$temp_arr_data)
    {
        foreach ($asset_data as $asset_key=>$asset_val)
        {
            switch ($asset_key)
            {
                case 'video':
                    foreach ($asset_val as $val)
                    {
                        $obj_sync = new standard_sync_source(array('cp_id'=>$cp_id,'cp_name'=>$temp_arr_data[$cp_id]['nns_name']),$temp_arr_data[$cp_id]['nns_config'],'',$cp_id);
                        $obj_sync->import->download_img_enabled = false;
                        $obj_sync->no_need_change_info = false;
                        $re = $obj_sync->modify_asset($val['data'],$val['video_id']);
                        if($re['ret'] !=0)
                        {
                            return $re;
                        }
                        unset($obj_sync);
                    }
                    break;
                case 'index':
                    foreach ($asset_val as $val)
                    {
                        $obj_sync = new standard_sync_source(array('cp_id'=>$cp_id,'cp_name'=>$temp_arr_data[$cp_id]['nns_name']),$temp_arr_data[$cp_id]['nns_config'],'',$cp_id);
                        $obj_sync->import->download_img_enabled = false;
                        $obj_sync->no_need_change_info = false;
                        $re = $obj_sync->modify_video_clip($val['data'],$val['video_id'],$val['index_id']);
                        if($re['ret'] !=0)
                        {
                            return $re;
                        }
                        unset($obj_sync);
                    }
                    break;
                case 'media':
                    foreach ($asset_val as $val)
                    {
                        $obj_sync = new standard_sync_source(array('cp_id'=>$cp_id,'cp_name'=>$temp_arr_data[$cp_id]['nns_name']),$temp_arr_data[$cp_id]['nns_config'],'',$cp_id);
                        $obj_sync->import->download_img_enabled = false;
                        $obj_sync->no_need_change_info = false;
                        $re = $obj_sync->import_video_file($val['data'],$val['video_id'],$val['index_id'],$val['media_id']);
                        if($re['ret'] !=0)
                        {
                            return $re;
                        }
                        unset($obj_sync);
                    }
                    break;
            }
        }
        return $this->_return_data(0,'ok');
    }
    
    
    /**
     * 生产媒资
     * @param unknown $arr_asset_info
     */
    public function make_asset($arr_asset_info,$cp_id)
    {
        $data = array();
        if(!isset($arr_asset_info['video']) || !isset($arr_asset_info['media']))
        {
            return $data;
        }
        $flag = (isset($arr_asset_info['video']['updatestr']) && $arr_asset_info['video']['updatestr'] == '已完结') ? true : false;
        if(!is_array($arr_asset_info['media']['itemvideos']) || empty($arr_asset_info['media']['itemvideos']))
        {
            return $data;
        }
        $asset_site_num = (int)$this->arr_params['bk_queue_config']['nns_ext_info']['asset_site_num'] >0 ? (int)$this->arr_params['bk_queue_config']['nns_ext_info']['asset_site_num'] : 3;
        $max = 1;
        $arr_site = array();
        foreach ($arr_asset_info['media']['itemvideos'] as $media_key=>$media_val)
        {
            if(!in_array($media_key, $this->arr_full_assets_site))
            {
                continue;
            }
            if(count($arr_site) >=$asset_site_num)
            {
                if(!in_array($media_key, $arr_site))
                {
                    continue;
                }
            }
            else
            {
                $arr_site[] = $media_key;
            }
            if(empty($media_val) || !is_array($media_val))
            {
                continue;
            }
            foreach ($media_val as $index=>$url_val)
            {
                if(strlen($url_val) <1)
                {
                    continue;
                }
                if($max < $index)
                {
                    $max = $index;
                }
                $data[$index][$media_key] = $url_val;
            }
        }
        if(empty($data) || empty($arr_site))
        {
            return $data;
        }
        $last_data = array();
        $video_import_id = $arr_asset_info['video']['id'];
        if(empty($video_import_id))
        {
            return $data;
        }
        $arr_asset_info['video']['name'] = htmlspecialchars($arr_asset_info['video']['name'], ENT_QUOTES);
        if(strlen($arr_asset_info['video']['name'])<1)
        {
            return $data;
        }
        $arr_asset_info['video']['duration'] = isset($arr_asset_info['video']['duration']) ? (int) $arr_asset_info['video']['duration'] * 60 : 0;
        $video_content = array(
            'Name'=>$arr_asset_info['video']['name'],
            'CategoryName'=>$arr_asset_info['video']['class'],
            'ReleaseYear'=>$arr_asset_info['video']['release'],
            'Kind'=>str_replace(',', '/', $arr_asset_info['video']['tags']),
            'SearchName'=>$arr_asset_info['video']['name'],
            'DirectorDisplay'=>(is_array($arr_asset_info['video']['writers']) && !empty($arr_asset_info['video']['writers'])) ? implode('/', $arr_asset_info['video']['writers']) : '',
            'AliasName'=>$arr_asset_info['video']['oname'],
            'EnglishName'=>$arr_asset_info['video']['ename'],
            'ActorDisplay'=>(is_array($arr_asset_info['video']['stars_all']) && !empty($arr_asset_info['video']['stars_all'])) ? implode('/', $arr_asset_info['video']['stars_all']) : '',
            'Tags'=>'27,28,29,30,31,',
            'OriginalCountry'=>$arr_asset_info['video']['country'],
            'VolumnCount'=>$max,
            'bigpic'=>'',
            'square_img'=>$arr_asset_info['video']['photo_s'],
            'smallpic'=>'',
            'middlepic'=>'',
            'verticality_img'=>'',
            'horizontal_img'=>$arr_asset_info['video']['photo_h'],
            'Description'=>$arr_asset_info['video']['intro'],
            'WriterDisplay'=>(is_array($arr_asset_info['video']['writers']) && !empty($arr_asset_info['video']['writers'])) ? implode('/', $arr_asset_info['video']['writers']) : '',
            'Language'=>$arr_asset_info['video']['language'],
            'Duration'=>$arr_asset_info['video']['duration'],
            'thrid_party_info'=>$arr_site,
        );
        $last_data['video'][] = array(
            'video_id'=>$video_import_id,
            'data'=>$video_content,
        );
        $index_content = array();
        $str_year = (isset($arr_asset_info['video']['release']) && !empty($arr_asset_info['video']['release'])) ? date("Y",strtotime($arr_asset_info['video']['release'])) : date('Y');
        $index = 0;
        foreach ($data as $key=>$val)
        {
            if(strlen($key) >3)
            {
                $str_name = '期';
                $index++;
            }
            else
            {
                $index = $key;
                $str_name = '集';
            }
            
            $index_import_id = $video_import_id."_".$index;
            $index_content=array(
                'Sequence'=>$index,
                'Name'=>$video_content['Name']."第{$index}{$str_name}",
                'Duration'=>$arr_asset_info['video']['duration'],
                'Description'=>'',
                'WriterDisplay'=>$video_content['WriterDisplay'],
                'ActorDisplay'=>$video_content['ActorDisplay'],
                'ViewPoint'=>'',
                'Tags'=>'27,28,29,30,31,',
                'Language'=>$video_content['Language'],
                'OriginalCountry'=>$video_content['OriginalCountry'],
                'KeyWords'=>'',
                'ReleaseYear'=>$str_year,
                'pic'=>'',
                'thrid_party_info'=>array_keys($val),
            );
            $last_data['index'][] = array(
                'video_id'=>$video_import_id,
                'index_id'=>$index_import_id,
                'data'=>$index_content,
            );
            $media_import_id = $index_import_id."_media";
            $media_content=array(
                'Name'=>$video_content['Name']."第{$index}{$str_name}",
                'MediaMode'=>'hd',
                'Resolution'=>6,
                'FileSize'=>'8081',
                'BitRateType'=>'4097',
                'Duration'=>$arr_asset_info['video']['duration'],
                'VideoType'=>'H264',
                'FileURL'=>'',
                'Tags'=>'27,28,29,30,31,',
                'conf_info'=>array('import_cdn_mode'=>$cp_id),
                'thrid_party_playurls'=>$val,
            );
            $last_data['media'][] = array(
                'video_id'=>$video_import_id,
                'index_id'=>$index_import_id,
                'media_id'=>$media_import_id,
                'data'=>$media_content,
            );
        }
        $last_data['flag'] = $flag;
        return $last_data;
    }
    
    /**
     * 处理媒资名称
     * @param n $asset_name
     */
    public function handel_asset_name($asset_name)
    {
        return $asset_name;
    }
    
    /**
     * curl 获取信息
     * @param string $asset_import_id
     * @param string $asset_name
     */
    public function get_content_by_third($asset_import_id=null,$asset_name=null)
    {
        $last_data = array();
        if(strlen($asset_import_id) <1 && strlen($asset_name)<1)
        {
            return $this->_return_data(0,'$asset_import_id为空或者$asset_name为空');
        }
        $asset_info_url = $this->arr_params['bk_queue_config']['nns_ext_info']['asset_info_url'];
        $asset_info_url = (strlen($asset_import_id) >0) ? $asset_info_url."&id=".$asset_import_id : $asset_info_url."&q=".$asset_name;
        $obj_curl = new public_sync_source();
        $arr_asset_info = $obj_curl->public_get_curl_content($asset_info_url,40);
        unset($obj_curl);
        if($arr_asset_info["ret"] != 0)
        {
            return $this->_return_data(1,"[无效url]{$asset_info_url}");
        }
        $arr_asset_info = isset($arr_asset_info['data_info']) ? $arr_asset_info['data_info'] : '';
        if(!$this->is_json($arr_asset_info))
        {
            return $this->_return_data(1,"请求接口[{$asset_info_url}]获取的数据是非JSON:".var_export($arr_asset_info,true));
        }
        $arr_asset_info=json_decode($arr_asset_info,true);
        if(!isset($arr_asset_info['id']) || strlen($arr_asset_info['id']) <1)
        {
            return $this->_return_data(1,"请求接口[{$asset_info_url}]获取媒资基本数据有问题ID为空:".var_export($arr_asset_info,true));
        }
        $asset_play_info_url = $this->arr_params['bk_queue_config']['nns_ext_info']['asset_play_info_url']."&id=".$arr_asset_info['id'];
        $obj_curl = new public_sync_source();
        $arr_media_info = $obj_curl->public_get_curl_content($asset_play_info_url,40);
        unset($obj_curl);
        $arr_media_info = isset($arr_media_info['data_info']) ? $arr_media_info['data_info'] : '';
        if(!$this->is_json($arr_media_info))
        {
            return $this->_return_data(1,"请求接口[{$asset_play_info_url}]获取的数据是非JSON:".var_export($arr_media_info,true));
        }
        $arr_media_info=json_decode($arr_media_info,true);
        if(!isset($arr_media_info['itemvideos']) || empty($arr_media_info['itemvideos']))
        {
            return $this->_return_data(1,"请求接口[{$asset_play_info_url}]获取播放列表为空:".var_export($arr_media_info,true));
        }
        return $this->_return_data(0,"请求接口[{$asset_play_info_url}]OK",array('video'=>$arr_asset_info,'media'=>$arr_media_info));
    }
}
$arr_files = pathinfo(__FILE__);
$file_name = $arr_files['filename'];
$timer_execute = new timer_execute($file_name, $file_name,__FILE__,'thrid_full_assests');
$timer_execute->run();
